{% extends "base_generic.html" %}
{% load static %}
{% load i18n %}

{% block content %}
  <h1>Title: {{ book.title }}</h1>

  {% if book.image %}
    <img src="{{ book.image.url }}" alt="{{ book.title }} {% trans "cover" %}" class="img-fluid mb-3" style="max-width: 200px; height: auto;">
  {% endif %}
  <p><strong>{% trans "Author" %}：</strong> <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a></p>
  <p><strong>{% trans "Summary" %}：</strong> {{ book.summary }}</p>
  <p><strong>{% trans "ISBN" %}：</strong> {{ book.isbn }}</p>
  <p><strong>{% trans "Language" %}：</strong> {{ book.language }}</p>
  <p><strong>{% trans "Genre" %}：</strong> {% for genre in book.genre.all %} {{ genre }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>
  <p><strong>{% trans "Average rating" %}：</strong> {{ avg_rating|default:_('No rating yet') }}</p>
  {% if user.is_authenticated %}
    <form method="post" id="rating-form">
      {% csrf_token %}
      <div class="star-rating">
        {% for i in '54321' %}
          <input type="radio" id="star{{ i }}" name="rating" value="{{ i }}" {% if user_rating and user_rating|stringformat:"i" == i %}checked{% endif %}>
          <label for="star{{ i }}" title="{{ i }} stars">&#9733;</label>
        {% endfor %}
      </div>
      <button type="submit">{% trans "Submit rating" %}</button>
    </form>
    {% if user_rating %}
      <p>{% trans "You have rated" %}：{{ user_rating }}</p>
    {% endif %}
  {% else %}
    <p>{% trans "Please log in to rate." %}</p>
  {% endif %}
  <style>
  .star-rating {
    direction: rtl;
    display: inline-flex;
  }
  .star-rating input[type="radio"] {
    display: none;
  }
  .star-rating label {
    font-size: 2em;
    color: #ddd;
    cursor: pointer;
  }
  .star-rating input[type="radio"]:checked ~ label,
  .star-rating label:hover,
  .star-rating label:hover ~ label {
    color: #ffc700;
  }
  </style>

  <div style="margin-left:20px;margin-top:20px">
    <h4>{% trans "Copies" %}</h4>

    {% for copy in book.bookinstance_set.all %}
    <hr>
    <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}">{{ copy.get_status_display }}</p>
    {% if copy.status != 'a' %}<p><strong>{% trans "Due to be returned" %}:</strong> {{copy.due_back}}</p>{% endif %}
    <p><strong>{% trans "Imprint" %}：</strong> {{copy.imprint}}</p>
    <p class="text-muted"><strong>{% trans "Id" %}：</strong> {{copy.id}}</p>
    {% if user.is_authenticated %}
        {% if copy.is_borrowed %}
            {% if copy.borrower == user %}
                <a href="{% url 'catalog:return-book' copy.id %}" class="btn btn-warning">{% trans "Return Book" %}</a>
            {% else %}
                <p class="text-muted">{% trans "Borrowed by another user" %}</p>
            {% endif %}
        {% else %}
            <a href="{% url 'catalog:borrow-book' copy.id %}" class="btn btn-primary">{% trans "Borrow Book" %}</a>
        {% endif %}
    {% else %}
        <p class="text-muted">{% trans "Please log in to borrow books" %}</p>
    {% endif %}
    {% endfor %}
  </div>

  <h4>{% trans "Reviews" %}</h4>
  {% for review in reviews %}
    <div class="review-item mb-4 p-3 border rounded" data-review-id="{{ review.id }}">
      <strong>{{ review.user.username }}</strong> {{ review.created_at|date:"Y-m-d H:i" }}<br>
      <p class="mb-2">{{ review.content|linebreaks }}</p>

      {% if user.is_authenticated %}
      <div class="review-actions mt-2 mb-3">
          <button type="button" class="btn btn-sm {% if review.user_likes %}btn-warning unlike-review-btn{% else %}btn-outline-success like-review-btn{% endif %}" data-review-id="{{ review.id }}" data-liked="{% if review.user_likes %}true{% else %}false{% endif %}">
              {% if review.user_likes %}<i class="bi bi-hand-thumbs-down"></i> {% trans "Unlike" %}{% else %}<i class="bi bi-hand-thumbs-up"></i> {% trans "Like" %}{% endif %}
          </button>
          <span class="like-count me-3">{{ review.likes.count }}</span>

          <button type="button" class="btn btn-sm {% if review.user_favorites %}btn-outline-danger unfavorite-review-btn{% else %}btn-outline-primary favorite-review-btn{% endif %}" data-review-id="{{ review.id }}" data-favorited="{% if review.user_favorites %}true{% else %}false{% endif %}">
              {% if review.user_favorites %}<i class="bi bi-heartbreak"></i> {% trans "Unfavorite" %}{% else %}<i class="bi bi-heart"></i> {% trans "Favorite" %}{% endif %}
          </button>
          <span class="favorite-count">{{ review.favorites.count }}</span>

          <button type="button" class="btn btn-sm btn-outline-secondary comment-review-btn ms-3" data-review-id="{{ review.id }}">{% trans "Comment" %}</button>
      </div>

      <div class="review-comment-form-container mt-2" id="review-comment-form-{{ review.id }}" style="display:none;">
          <textarea class="form-control mb-2" rows="2" placeholder="{% trans 'Write a comment on this review...' %}" id="review-comment-content-{{ review.id }}"></textarea>
          <button type="button" class="btn btn-primary btn-sm submit-review-comment-btn" data-review-id="{{ review.id }}">{% trans "Post Comment" %}</button>
      </div>
      {% endif %}

      <div class="review-comments-list mt-3" id="review-comments-list-{{ review.id }}">
          {% for comment in review.top_level_comments %}
              {% include 'catalog/review_comment_snippet.html' with comment=comment user=user %}
          {% empty %}
              <p class="text-muted no-review-comments">{% trans "No comments yet." %}</p>
          {% endfor %}
      </div>
    </div>
    <hr>
  {% empty %}
    <p>{% trans "No reviews yet." %}</p>
  {% endfor %}

  {% if user.is_authenticated %}
    <form method="post">
      {% csrf_token %}
      {{ review_form.as_p }}
      <button type="submit" name="review_submit">{% trans "Submit review" %}</button>
    </form>
  {% else %}
    <p>{% trans "Please log in to comment." %}</p>
  {% endif %}

  <p>
    <strong>{% trans "Likes" %}：</strong> {{ book.likes.count }}
    {% if user.is_authenticated %}
      {% if user_has_liked %}
        <a href="{% url 'catalog:unlike-book' book.pk %}" class="btn btn-warning btn-sm">
          <i class="bi bi-hand-thumbs-down"></i> {% trans "Unlike" %}
        </a>
      {% else %}
        <a href="{% url 'catalog:like-book' book.pk %}" class="btn btn-success btn-sm">
          <i class="bi bi-hand-thumbs-up"></i> {% trans "Like" %}
        </a>
      {% endif %}
    {% else %}
      <span>{% trans "Please log in to like." %}</span>
    {% endif %}
  </p>
  <p>
    <strong>{% trans "Favorites" %}：</strong> {{ book.favorites.count }}
    {% if user.is_authenticated %}
      {% if user_has_favorited %}
        <a href="{% url 'catalog:unfavorite-book' book.pk %}" class="btn btn-outline-danger btn-sm">
          <i class="bi bi-heartbreak"></i> {% trans "Unfavorite" %}
        </a>
      {% else %}
        <a href="{% url 'catalog:favorite-book' book.pk %}" class="btn btn-outline-primary btn-sm">
          <i class="bi bi-heart"></i> {% trans "Favorite" %}
        </a>
      {% endif %}
    {% else %}
      <span>{% trans "Please log in to favorite." %}</span>
    {% endif %}
  </p>

{% endblock %}

{% block extra_css %}
<style>
.review-comment {
    background-color: #f8f9fa;
    border-radius: .25rem;
}
.review-comment .review-comment {
    margin-left: 20px; /* Indent replies */
    background-color: #e9ecef;
}
.review-actions button,
.review-comment-actions button {
    margin-right: 5px;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
    const getCookie = (name) => {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    };

    // Translated strings for JavaScript
    const replyText = '{% trans "Reply" %}';
    const likeText = '{% trans "Like" %}';
    const unlikeText = '{% trans "Unlike" %}';
    const favoriteText = '{% trans "Favorite" %}';
    const unfavoriteText = '{% trans "Unfavorite" %}';
    const writeReplyText = '{% trans "Write your reply..." %}';
    const postCommentText = '{% trans "Post Comment" %}';

    function addReviewCommentToDOM(commentData, parentContainerId = null) {
        const newCommentHtml = `
            <div class="review-comment mb-3 p-3 border rounded" data-comment-id="${commentData.id}">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <strong>${commentData.user}</strong>
                    <small class="text-muted">${commentData.created_at}</small>
                </div>
                <p class="mb-0">${commentData.content}</p>
                {% if user.is_authenticated %}
                <div class="review-comment-actions mt-2">
                    <button type="button" class="btn btn-sm btn-outline-secondary reply-review-comment-btn" data-comment-id="${commentData.id}">${replyText}</button>
                    <button type="button" class="btn btn-sm btn-outline-success like-review-comment-btn" data-comment-id="${commentData.id}" data-liked="false">${likeText}</button>
                    <span class="like-count">0</span>
                    <button type="button" class="btn btn-sm btn-outline-info favorite-review-comment-btn" data-comment-id="${commentData.id}" data-favorited="false">${favoriteText}</button>
                    <span class="favorite-count">0</span>
                </div>
                <div class="reply-review-comment-form-container mt-2" id="reply-review-comment-form-${commentData.id}" style="display:none;">
                    <textarea class="form-control mb-2" rows="2" placeholder="${writeReplyText}" id="reply-review-comment-content-${commentData.id}"></textarea>
                    <button type="button" class="btn btn-primary btn-sm submit-review-reply-btn" data-parent-id="${commentData.id}">${postCommentText}</button>
                </div>
                {% endif %}
                <div class="review-comments-list mt-3" id="review-comments-list-${commentData.id}"></div>
            </div>
        `;

        if (parentContainerId) {
            const parentCommentsList = document.getElementById(parentContainerId);
            if (parentCommentsList) {
                parentCommentsList.insertAdjacentHTML('beforeend', newCommentHtml);
            }
        } else {
            // This case should not happen if called correctly, as comments are nested under reviews
            console.error("addReviewCommentToDOM called without a parentContainerId for a top-level comment.");
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Review Like/Unlike
        document.querySelectorAll('.like-review-btn, .unlike-review-btn').forEach(button => {
            button.addEventListener('click', async function() {
                const reviewId = this.dataset.reviewId;
                const isLiked = this.dataset.liked === 'true';
                const url = isLiked ? '{% url "catalog:unlike_review_comment" 0 %}'.replace('/0/', `/${reviewId}/`) : '{% url "catalog:like_review_comment" 0 %}'.replace('/0/', `/${reviewId}/`);
                const likeCountSpan = this.nextElementSibling;

                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken')
                        }
                    });
                    const data = await response.json();

                    if (response.ok && data.status === 'success') {
                        this.dataset.liked = (!isLiked).toString();
                        this.textContent = isLiked ? likeText : unlikeText;
                        this.classList.toggle('btn-warning', !isLiked);
                        this.classList.toggle('unlike-review-btn', !isLiked);
                        this.classList.toggle('btn-outline-success', isLiked);
                        this.classList.toggle('like-review-btn', isLiked);
                        likeCountSpan.textContent = data.likes;
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred.');
                }
            });
        });

        // Review Favorite/Unfavorite
        document.querySelectorAll('.favorite-review-btn, .unfavorite-review-btn').forEach(button => {
            button.addEventListener('click', async function() {
                const reviewId = this.dataset.reviewId;
                const isFavorited = this.dataset.favorited === 'true';
                const url = isFavorited ? '{% url "catalog:unfavorite_review_comment" 0 %}'.replace('/0/', `/${reviewId}/`) : '{% url "catalog:favorite_review_comment" 0 %}'.replace('/0/', `/${reviewId}/`);
                const favoriteCountSpan = this.nextElementSibling;

                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken')
                        }
                    });
                    const data = await response.json();

                    if (response.ok && data.status === 'success') {
                        this.dataset.favorited = (!isFavorited).toString();
                        this.textContent = isFavorited ? favoriteText : unfavoriteText;
                        this.classList.toggle('btn-outline-danger', !isFavorited);
                        this.classList.toggle('unfavorite-review-btn', !isFavorited);
                        this.classList.toggle('btn-outline-primary', isFavorited);
                        this.classList.toggle('favorite-review-btn', isFavorited);
                        favoriteCountSpan.textContent = data.favorites;
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred.');
                }
            });
        });

        // Review Comment button click (show/hide form)
        document.querySelectorAll('.comment-review-btn').forEach(button => {
            button.addEventListener('click', function() {
                const reviewId = this.dataset.reviewId;
                const formContainer = document.getElementById(`review-comment-form-${reviewId}`);
                if (formContainer) {
                    formContainer.style.display = formContainer.style.display === 'none' ? 'block' : 'none';
                    if (formContainer.style.display === 'block') {
                        formContainer.querySelector('textarea').focus();
                    }
                }
            });
        });

        // Submit Review Comment
        document.querySelectorAll('.submit-review-comment-btn').forEach(button => {
            button.addEventListener('click', async function() {
                const reviewId = this.dataset.reviewId;
                const commentContentInput = document.getElementById(`review-comment-content-${reviewId}`);
                const content = commentContentInput.value.trim();

                if (!content) {
                    alert('Comment content cannot be empty.');
                    return;
                }

                try {
                    const response = await fetch('{% url "catalog:comment_review" 0 %}'.replace('/0/', `/${reviewId}/`), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': getCookie('csrftoken')
                        },
                        body: JSON.stringify({ content: content })
                    });
                    const data = await response.json();

                    if (response.ok && response.status === 201) {
                        addReviewCommentToDOM(data, `review-comments-list-${reviewId}`);
                        commentContentInput.value = '';
                        document.getElementById(`review-comment-form-${reviewId}`).style.display = 'none';
                         // Remove 'No comments yet.' if it exists
                        const noCommentsMsg = document.querySelector(`#review-comments-list-${reviewId} .no-review-comments`);
                        if (noCommentsMsg) {
                            noCommentsMsg.remove();
                        }
                    } else {
                        alert('Error: ' + (data.error || 'Unknown error'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred.');
                }
            });
        });

        // Reply to Review Comment button click (show/hide form)
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('reply-review-comment-btn')) {
                const commentId = e.target.dataset.commentId;
                const formContainer = document.getElementById(`reply-review-comment-form-${commentId}`);
                if (formContainer) {
                    formContainer.style.display = formContainer.style.display === 'none' ? 'block' : 'none';
                    if (formContainer.style.display === 'block') {
                        formContainer.querySelector('textarea').focus();
                    }
                }
            }
        });

        // Submit Reply to Review Comment
        document.addEventListener('click', async function(e) {
            if (e.target.classList.contains('submit-review-reply-btn')) {
                const parentId = e.target.dataset.parentId;
                const replyContentInput = document.getElementById(`reply-review-comment-content-${parentId}`);
                const content = replyContentInput.value.trim();

                if (!content) {
                    alert('Reply content cannot be empty.');
                    return;
                }

                try {
                    const response = await fetch('{% url "catalog:comment_review" 0 %}'.replace('/0/', `/${parentId}/`), { // Using comment_review for replies as well
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': getCookie('csrftoken')
                        },
                        body: JSON.stringify({ content: content, parent_comment_id: parentId })
                    });
                    const data = await response.json();

                    if (response.ok && response.status === 201) {
                        addReviewCommentToDOM(data, `review-comments-list-${parentId}`);
                        replyContentInput.value = '';
                        document.getElementById(`reply-review-comment-form-${parentId}`).style.display = 'none';
                    } else {
                        alert('Error: ' + (data.error || 'Unknown error'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred.');
                }
            }
        });

        // Review Comment Like/Unlike
        document.addEventListener('click', async function(e) {
            if (e.target.classList.contains('like-review-comment-btn') || e.target.closest('.like-review-comment-btn')) {
                const button = e.target.classList.contains('like-review-comment-btn') ? e.target : e.target.closest('.like-review-comment-btn');
                const commentId = button.dataset.commentId;
                const isLiked = button.dataset.liked === 'true';
                const url = isLiked ? '{% url "catalog:unlike_review_comment" 0 %}'.replace('/0/', `/${commentId}/`) : '{% url "catalog:like_review_comment" 0 %}'.replace('/0/', `/${commentId}/`);
                const likeCountSpan = button.nextElementSibling;

                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken')
                        }
                    });
                    const data = await response.json();

                    if (response.ok && data.status === 'success') {
                        button.dataset.liked = (!isLiked).toString();
                        button.textContent = isLiked ? likeText : unlikeText;
                        button.classList.toggle('btn-warning', !isLiked);
                        button.classList.toggle('btn-outline-success', isLiked);
                        likeCountSpan.textContent = data.likes;
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred.');
                }
            }
        });

        // Review Comment Favorite/Unfavorite
        document.addEventListener('click', async function(e) {
            if (e.target.classList.contains('favorite-review-comment-btn') || e.target.closest('.favorite-review-comment-btn')) {
                const button = e.target.classList.contains('favorite-review-comment-btn') ? e.target : e.target.closest('.favorite-review-comment-btn');
                const commentId = button.dataset.commentId;
                const isFavorited = button.dataset.favorited === 'true';
                const url = isFavorited ? '{% url "catalog:unfavorite_review_comment" 0 %}'.replace('/0/', `/${commentId}/`) : '{% url "catalog:favorite_review_comment" 0 %}'.replace('/0/', `/${commentId}/`);
                const favoriteCountSpan = button.nextElementSibling;

                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken')
                        }
                    });
                    const data = await response.json();

                    if (response.ok && data.status === 'success') {
                        button.dataset.favorited = (!isFavorited).toString();
                        button.textContent = isFavorited ? favoriteText : unfavoriteText;
                        button.classList.toggle('btn-outline-danger', !isFavorited);
                        button.classList.toggle('btn-outline-primary', isFavorited);
                        favoriteCountSpan.textContent = data.favorites;
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred.');
                }
            }
        });
    });
</script>
{% endblock %}

